import { Button, Form, message } from 'antd';
import ProForm, { ModalForm, ProFormRadio, ProFormText } from '@ant-design/pro-form';
import type { FormCarouselType } from '@/pages/Carousel/data';
import UploadImage from '@/components/UploadImage';
import { updateCarousel } from '../service';
const formLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
interface UpdateFormProps {
  setRefreshCount: any;
  formVals: FormCarouselType;
}
const UpdateModalForm = (props: UpdateFormProps) => {
  const { formVals, setRefreshCount } = props;
  const [form] = Form.useForm();
  /**
   * 更新节点
   * @param fields
   */
  const handleUpdate = async (fields: FormCarouselType) => {
    const hide = message.loading('正在更新');
    try {
      const res = await updateCarousel({
        ...fields,
        id: formVals.id,
      });
      hide();
      if (res.success) {
        setRefreshCount((count: any) => count + 1);
        message.success('更新成功');
      } else {
        message.error('更新失败,请重试');
      }
      return true;
    } catch (error) {
      hide();
      message.error('更新失败,请重试');
      return false;
    }
  };
  return (
    <ModalForm
      form={form}
      layout="horizontal"
      {...formLayout}
      title="编辑轮播图"
      modalProps={{
        onCancel: () => form.resetFields(),
      }}
      initialValues={{
        image_url: formVals.image_url,
        desc: formVals.desc,
        is_locked: formVals.is_locked,
      }}
      trigger={
        <Button size="small" type="primary">
          编辑
        </Button>
      }
      onFinish={async () => {
        form
          .validateFields()
          .then((fieldsValue) => {
            handleUpdate(fieldsValue);
          })
          .catch(() => {});
        return true;
      }}
    >
      <ProForm.Item
        key="image_url"
        name="image_url"
        label="轮播图"
        getValueFromEvent={(e) => {
          return e.response.url;
        }}
        rules={[{ required: true, message: '请上传轮播图' }]}
      >
        <UploadImage forValue="carsoul" />
      </ProForm.Item>
      <ProFormText
        width={256}
        key="desc"
        name="desc"
        label="图片描述"
        rules={[{ required: true, message: '请输入图片描述' }]}
      />
      <ProFormRadio.Group
        width={256}
        name="is_locked"
        key="is_locked"
        label="是否在前台展示"
        options={[
          {
            label: '是',
            value: 0,
          },
          {
            label: '否',
            value: 1,
          },
        ]}
      />
    </ModalForm>
  );
};
export default UpdateModalForm;
